package com.stylefeng.guns.modular.huamao.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.common.GetOrderNum;
import com.stylefeng.guns.modular.huamao.dao.*;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.service.IAccountShopService;
import com.stylefeng.guns.modular.huamao.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.modular.huamao.service.ISupplementService;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 手动补单 服务实现类
 * 
 * @author gxz
 *
 */
@Service
public class SupplementServiceImpl extends ServiceImpl<SupplementMapper, SupplementList> implements ISupplementService {

	@Autowired
	private SupplementMapper sm;
	@Autowired
	private LogScoreMapper logScoreMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private LogCashMapper logCashMapper;
	@Autowired
    private LogKaiyuanMapper logKaiyuanMapper;
	@Autowired
    private LogStockscoreMapper logStockscoreMapper;
	@Autowired
    private AccountShopMapper accountShopMapper;
	@Autowired
	private IAccountShopService accountShopService;
	@Autowired
	private UsersMapper usersMapper;
	@Autowired
	private AccountOperationMapper accountOperationMapper;

	// 校验用户名或手机号是否存在
	@Override
	public SupplementList checkUser(SupplementList supplementList) {
		return sm.checkUser(supplementList);
	}

	// 添加记录
	@Override
	public Map<String,Object> add(SupplementList supplementList) {
		Map<String,Object> map = new HashMap<String,Object>();
		//查看操作对象
		//实时查询用户账户
        Integer userId = supplementList.getUserId();
		Account account = accountMapper.selectAccountBuyuserId(userId);
		BigDecimal preScore = account.getScore();
		BigDecimal preCash = account.getCash();
		BigDecimal preKaiyuan = account.getKaiyuan();
		String remark = "";
		/**
		 * 操作对象 1积分 2现金 3华宝 4库存积分（object）
		 */
		if(supplementList.getObject() == 1){
			if(supplementList.getType() == 1){
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台添加";
				}
				this.insertLogScore(0,14,"8",preScore,remark,supplementList.getNum(),1,supplementList.getUserId());
				//修改用户账户信息

                account.setTotalScore(account.getTotalScore().add(supplementList.getNum()));
                account.setScore(account.getScore().add(supplementList.getNum()));
                accountMapper.updateById(account);
			}else{
				//先判断用户积分够不够，够就扣除，不够返回
				if(account.getScore().compareTo(supplementList.getNum()) == -1){
					map.put("code",0);
					map.put("msg","该用户积分不足以支付本次扣除！");
					return map;
				}
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台减少";
				}
				this.insertLogScore(0,32,"8",preScore,remark,supplementList.getNum(),-1,supplementList.getUserId());
				//修改用户账户信息
				account.setScore(account.getScore().subtract(supplementList.getNum()));
				accountMapper.updateById(account);
			}
		}else if(supplementList.getObject() == 2){
			if(supplementList.getType() == 1){
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台添加";
				}
				this.insertLogCash(1,0,supplementList.getUserId(),"8",preCash,remark,6,supplementList.getNum());
				account.setTotalCash(account.getTotalCash().add(supplementList.getNum()));
				account.setCash(account.getCash().add(supplementList.getNum()));
				accountMapper.updateById(account);
			}else{
				//先判断用户现金够不够，够就扣除，不够返回
				if(account.getCash().compareTo(supplementList.getNum()) == -1){
					map.put("code",0);
					map.put("msg","该用户现金不足以支付本次扣除！");
					return map;
				}
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台减少";
				}
                this.insertLogCash(-1,0,supplementList.getUserId(),"8",preCash,remark,34,supplementList.getNum());
                account.setCash(account.getCash().subtract(supplementList.getNum()));
                accountMapper.updateById(account);
			}
		}else if(supplementList.getObject() == 3){
			if(supplementList.getType() == 1){
                if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
                    remark = supplementList.getRemark();
                }else{
                    remark = "后台添加";
                }
                this.insertLogKaiyuan(10,0,supplementList.getUserId(),"8",preKaiyuan,1,supplementList.getNum(),remark);
			    account.setTotalKaiyuan(account.getTotalKaiyuan().add(supplementList.getNum()));
			    account.setKaiyuan(account.getKaiyuan().add(supplementList.getNum()));
			    accountMapper.updateById(account);
			}else{
				//先判断用户华宝够不够，够就扣除，不够返回
				if(account.getKaiyuan().compareTo(supplementList.getNum()) == -1){
					map.put("code",0);
					map.put("msg","该用户华宝不足以支付本次扣除！");
					return map;
				}
                if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
                    remark = supplementList.getRemark();
                }else{
                    remark = "后台减少";
                }
                this.insertLogKaiyuan(40,0,supplementList.getUserId(),"8",preKaiyuan,-1,supplementList.getNum(),remark);
                account.setKaiyuan(account.getKaiyuan().subtract(supplementList.getNum()));
                accountMapper.updateById(account);
			}
		}else if(supplementList.getObject() == 4){
		   //先判断该用户是不是商家
			Users users = usersMapper.selectById(userId);
			if(users.getIsShop() == 0 && users.getIsStore() == 0){
				//不是商家
				map.put("code",0);
				map.put("msg","该用户不是商家，不能操作库存积分！");
				return map;
			}
			//查询商家信息
			AccountShop accountShop = new AccountShop();
			accountShop.setShopId(account.getShopId());
			EntityWrapper<AccountShop> entityWrapper = new EntityWrapper<AccountShop>(accountShop);
			AccountShop shop = accountShopService.selectOne(entityWrapper);
			BigDecimal preStockScore = shop.getStockScore();
			if(supplementList.getType() == 1){
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台添加";
				}
				this.insertStockScore(5,0,supplementList.getUserId(),"8",preStockScore,1,supplementList.getNum(),remark);
				shop.setTotalStockScore(shop.getTotalStockScore().add(supplementList.getNum()));
				shop.setStockScore(shop.getStockScore().add(supplementList.getNum()));
				accountShopMapper.updateById(shop);
			}else{
				//先判断商家库存积分够不够，够就扣除，不够返回
				if(shop.getStockScore().compareTo(supplementList.getNum()) == -1){
					map.put("code",0);
					map.put("msg","该商家库存积分不足以支付本次扣除！");
					return map;
				}
				if(supplementList.getRemark() != null && supplementList.getRemark() != ""){
					remark = supplementList.getRemark();
				}else{
					remark = "后台减少";
				}
				this.insertStockScore(6,0,supplementList.getUserId(),"8",preStockScore,-1,supplementList.getNum(),remark);
				shop.setStockScore(shop.getStockScore().subtract(supplementList.getNum()));
				accountShopMapper.updateById(shop);
			}
		}else if (supplementList.getObject()==5){
			JSONObject robject = new JSONObject();
			JSONObject result = this.checkNumber(supplementList.getUserPhone());
			/**
			 * 用来接收datas的值
			 */
			if(!result.getBoolean("isSuc")){
				map.put("code",0);
				map.put("msg","校验失败");
				return map;
			}else{
				robject  = result.getJSONObject("datas");
				/**
				 * 判断用户是否注册
				 */
				if(robject.getString("userID").equals("0")){
					map.put("code",0);
					map.put("msg","用户未在交易所注册");
					return map;
				}
			}

			String url = "https://api1.digsg.com/assets/recharge";

			/**
			 * 用户交易所的ID
			 */
			//Integer userID = rexchangeUser.getExchangeUserId();
			Integer userID = robject.getInteger("userID");
			String companyID = "1";
			String secretKey = "iL34.#dnZ2ubJJFt";
			/**
			 * MD5加密
			 */
			String key = Integer.toString(userID)+supplementList.getNum().toString()+companyID+secretKey;
			String md5Info = MD5Util.encrypt(key);

			Map<String,Object> maps = new HashMap<String, Object>();
			maps.put("userID",userID);
			maps.put("amount",supplementList.getNum().toString());
			maps.put("companyID",companyID);
			maps.put("md5Info",md5Info);
			/**
			 *调用用户充值接口
			 */
			String json =  HttpUtil.doPost(url,maps);
			JSONObject jsonObject = JSONObject.parseObject(json);
			if(jsonObject.getBoolean("isSuc")){

			}else{
				maps.put("code",0);
				maps.put("msg",jsonObject.getString("des"));
				return maps;
			}
		}
		Boolean b = sm.add(supplementList);
		map.put("code",1);
		map.put("msg","操作成功！");
		return map;

	}

	/**
	 * 判断用户是否注册交易所
	 * @param userPhone
	 * @return
	 */
	public JSONObject checkNumber(String userPhone){
		String url = "https://api1.digsg.com/user/register";
		String companyID = "1";

		String userMobile= userPhone;
		String secretKey = "iL34.#dnZ2ubJJFt";
		String key = userMobile+companyID+secretKey;
		String md5Info = MD5Util.encrypt(key);

		Map<String,Object> map = new HashMap<String, Object>();
		map.put("companyID",companyID);
		map.put("userMobile",userMobile);
		map.put("md5Info",md5Info);

		String json =  HttpUtil.doPost(url,map);
		return JSONObject.parseObject(json);

	}

	/**   插入积分流水
	 * @param fromId
	 * @param preScore
	 * @param remark
	 * @param score
	 * @param scoreType
	 * @param userId
	 * @return
	 */
	@Transactional
	public boolean insertLogScore(int fromId, int type, String firstNum, BigDecimal preScore, String remark, BigDecimal score, int scoreType, int userId){
		LogScore logScore=new LogScore();
		logScore.setCreateTime(new Date());
		logScore.setDataFlag(1);
		logScore.setFromId(fromId);
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate = sfDate.format(new Date());
		String num = GetOrderNum.getRandom620(2);
		logScore.setOrderNo(firstNum+strDate+num);
		logScore.setPreScore(preScore);
		logScore.setRemark(remark);
		logScore.setScore(score);
		logScore.setScoreType(scoreType);
		logScore.setType(type);
		logScore.setUserId(userId);
		Integer flag = logScoreMapper.insert(logScore);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}
	/**  现金流水
	 * @param cashType
	 * @param fromId
	 * @param userId
	 * @param firstNum
	 * @param preCash
	 * @param remark
	 * @param type
	 * @param cash
	 * @return
	 */
	@Transactional
	public boolean insertLogCash(Integer cashType,Integer fromId,Integer userId ,String firstNum,BigDecimal preCash,String remark,Integer type,BigDecimal cash){
		LogCash logCash=new LogCash();
		logCash.setCashType(cashType);
		logCash.setCreateTime(new Date());
		logCash.setDataFlag(1);
		logCash.setFromId(fromId);
		logCash.setUserId(userId);
		// 创建订单号
		SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		String strDate = sfDate.format(new Date());
		String num = GetOrderNum.getRandom620(2);
		logCash.setOrderNo(firstNum+strDate + num);
		logCash.setPreCash(preCash);
		logCash.setRemark(remark);
		logCash.setType(type);
		logCash.setCash(cash);
		int flag=logCashMapper.insert(logCash);
		if(flag==1){
			return true;
		}else{
			return false;
		}
	}

	//华宝流水
    public Integer insertLogKaiyuan(Integer type,Integer fromId,Integer userId,String firstNum,BigDecimal preKaiyuan,Integer kaiyuanType,BigDecimal kaiyuan,String remark){
        LogKaiyuan logKaiyuan = new LogKaiyuan();
        logKaiyuan.setType(type);
        logKaiyuan.setFromId(fromId);
        logKaiyuan.setUserId(userId);
        // 创建订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        logKaiyuan.setOrderNo(firstNum+strDate + num);
        logKaiyuan.setPreKaiyuan(preKaiyuan);
        logKaiyuan.setKaiyuanType(kaiyuanType);
        logKaiyuan.setKaiyuan(kaiyuan);
        logKaiyuan.setRemark(remark);
        logKaiyuan.setCreateTime(new Date());
        Integer insert = logKaiyuanMapper.insert(logKaiyuan);
        return insert;
    }

    //添加库存记录
    public Integer insertStockScore(Integer type,Integer fromId,Integer userId,String firstNum,BigDecimal preScore,Integer scoreType,BigDecimal score,String remark){
        LogStockscore logStockscore = new LogStockscore();
        logStockscore.setType(type);
        logStockscore.setFromId(fromId);
        logStockscore.setUserId(userId);
        // 生成订单号
        SimpleDateFormat sfDate = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String strDate = sfDate.format(new Date());
        String num = GetOrderNum.getRandom620(2);
        logStockscore.setOrderNo(firstNum + strDate + num);
        logStockscore.setPreScore(preScore);
        logStockscore.setScoreType(scoreType);
        logStockscore.setScore(score);
        logStockscore.setRemark(remark);
        logStockscore.setCreateTime(new Date());
        Integer insert = logStockscoreMapper.insert(logStockscore);
        return insert;
    }
}
